package com.example.demo.service.Impl;

import com.example.demo.entity.*;
import com.example.demo.exception.CustomException;
import com.example.demo.mapper.EmpExprMapper;
import com.example.demo.mapper.EmpMapper;
import com.example.demo.service.EmpLogService;
import com.example.demo.service.EmpService;
import com.example.demo.utils.JwtUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;


    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

//    public PageBean page(Integer page, Integer pageSize) {
//        // 1.调用mapper获取总记录数  total  [ select count(*) from emp;]
//        Long total = empMapper.getTotal();
//        //2.调用mapper获取分页列表数据 rows  [select e.name, e.gender,e.image,d.name,e.job from emp e left join dept d on e.dept_id = d.id limit 0, 5]
//        Integer start = (page-1) * pageSize;
//        List<Emp> EmpList = empMapper.getPage(start,pageSize);
//        //3.封装PageBean对象并返回
//        return new PageBean(total,EmpList);
//    }
    @Override
    public PageBean page(EmpQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(),param.getPageSize());

        //2.调用mapper的列表查询方法
        List<Emp> empList = empMapper.getPage(param);
        Page<Emp> p = (Page) empList;

        //3.封装PageBean对象并返回
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 保存员工信息
     * @param emp
     */
    @Transactional(rollbackFor = Exception.class)  //开启事务,rollbackFor指定处理所有异常，默认情况下只能处理运行时异常
    @Override
    public void save(Emp emp) {
        try {
            //1.补全基础属性
            emp.setPassword("123456");
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());

            //2.保存员工基本信息
            empMapper.insert(emp);

//        int test = 1/0;
            Integer  id = emp.getId();
            log.info(" id = {}",id);

            //3.保存员工的工作经历信息 - 批量
            List<EmpExpr> exprList = emp.getExprList();
            if(!CollectionUtils.isEmpty(exprList)){
                exprList.forEach(empExpr -> empExpr.setEmpId(id));
                empExprMapper.insertExpr(exprList);
            }
        } finally {
            // 无论新增员工成功与否，都需要添加操作日志
            EmpLog empLog = new EmpLog();
            empLog.setOperateTime(LocalDateTime.now());
            empLog.setInfo("插入emp信息: "+emp);
            empLogService.insertLog(empLog);
        }
    }

    @Transactional
    @Override
    public void deleteByids(List<Integer> ids) {
        //1.删除指定id的emp
        empMapper.deleteByIds(ids);
        //2.删除emp的emp_expr
        empExprMapper.deleteByempIds(ids);
    }

    @Override
    public Emp findById(Integer id) {
        //1.根据id查询员工信息
        Emp emp = empMapper.findById(id);
        //2.根据员工id查询员工工作经历
        List<EmpExpr> exprList = empExprMapper.findByEmpId(id);
        emp.setExprList(exprList);
        return emp;
    }

    @Transactional
    @Override
    public void update(Emp emp) {
        //1.补充基础数据
        emp.setUpdateTime(LocalDateTime.now());
        //2.更新员工基本信息
        empMapper.updateById(emp);
        //3.更新员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            //先删除所有经历
            empExprMapper.deleteByempIds(Arrays.asList(emp.getId()));
            //给每个工作经历设置员工id
            exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
            empExprMapper.insertExpr(exprList);
        }
    }

    @Override
    public List<Emp> getAllEmp() {
        return empMapper.getAllEmp();
    }

    /**
     * login
     * @return
     */
    @Override
    public EmpLoginInfo login(Emp  emp) {
        EmpLoginInfo empLoginInfo =  empMapper.login(emp);
        if (empLoginInfo != null){
            //1.生成令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",empLoginInfo.getId());
            claims.put("username",empLoginInfo.getUsername());

            String jwt = JwtUtils.generateJwt(claims);
            empLoginInfo.setToken(jwt);
            return empLoginInfo;
        }
        return null;
    }
}
